package com.ljh.dao;

import com.ljh.pojo.Books;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class BookMapperImpl extends HibernateDaoSupport implements BookMapper {
    @Autowired
    private SessionFactory sessionFactory;
    private Session getSession()
    {
        return sessionFactory.getCurrentSession();
    }
    public int addBook(Books books) {
        getSession().save(books);
        return 0;
    }
    public int deleteBookById(int id) {
        Books books=new Books();
        books.setBookID(id);
        getSession().delete(books);
        return 0;
    }

    public int updateBook(Books books) {
        getSession().update(books);
        return 0;
    }

    public Books queryBookById(int id) {
        List<Books> books=getSession().createQuery("from Books where bookID=?").setParameter(0,id).list();
        return books.get(0);
    }

    public List<Books> queryAllBook() {
        return (List<Books>)getSession().createQuery("from Books").list();
    }

    public List<Books> queryBookByName(String name) {
        return (List<Books>)getSession().createQuery("from Books where bookName like '%"+name+"%'").list();
    }

    public int updateBookCount(int bookid, int bookcount) {
        getSession().createQuery("update Books set bookCounts=bookCounts-? where bookID=?")
                .setParameter(0,bookcount)
                .setParameter(1,bookid)
                .executeUpdate();
        return 0;
    }
}
